import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  Select,
  DatePicker,
  InputNumber,
  message,
  Card,
  Row,
  Col,
  Skeleton
} from 'antd';
import FundsrecoverymanagementService from '../../services/FundsrecoverymanagementService';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

const UpdateFundsrecovery = () => {
  const [form] = Form.useForm();
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [dataLoading, setDataLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setDataLoading(true);
        const response = await FundsrecoverymanagementService.getFundsrecoverymanagementById(id);

        if (response.data) {
          // 转换日期字段为moment对象
          const data = {
            ...response.data,
            countryDate: response.data.countryDate ? moment(response.data.countryDate) : null,
            submissionTime: response.data.submissionTime ? moment(response.data.submissionTime) : null,
            approvalTime: response.data.approvalTime ? moment(response.data.approvalTime) : null
          };

          form.setFieldsValue(data);
        } else {
          message.error('未找到回款记录信息');
          navigate('/fundsrecoverymanagement');
        }
      } catch (error) {
        console.error('获取回款详情失败:', error);
        message.error('加载回款详情失败');
      } finally {
        setDataLoading(false);
      }
    };

    fetchData();
  }, [id, form, navigate]);

  const onFinish = async (values) => {
    try {
      setLoading(true);
      // 格式化日期字段
      // 修改为 ISO 格式或时间戳
      const formattedValues = {
        ...values,
        countryDate: values.countryDate?.toISOString(), // 或 .valueOf()
        submissionTime: values.submissionTime?.toISOString(),
        approvalTime: values.approvalTime?.toISOString()
      };

      await FundsrecoverymanagementService.updateFundsrecoverymanagement(id, formattedValues);
      message.success('回款记录更新成功！');
      navigate(`/fundsrecoverymanagement/funddetails/${id}`);
    } catch (error) {
      console.error('更新回款记录失败:', error);
      message.error('更新回款记录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (dataLoading) {
    return (
      <Card title="更新回款记录" bordered={false} style={{ margin: 20 }}>
        <Skeleton active paragraph={{ rows: 10 }} />
      </Card>
    );
  }

  return (
    <Card
      title="更新回款记录"
      bordered={false}
      style={{ margin: 20 }}
      extra={
        <Button onClick={() => navigate(`/fundsrecoverymanagement/funddetails/${id}`)}>
          返回详情
        </Button>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="系统编号"
              name="systemNumber"
              rules={[{ required: true, message: '请输入系统编号' }]}
            >
              <Input placeholder="请输入系统编号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="关联客户"
              name="relatedCustomer"
              rules={[{ required: true, message: '请输入关联客户' }]}
            >
              <Input placeholder="请输入关联客户" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="关联订单"
              name="relatedOrder"
              rules={[{ required: true, message: '请输入关联订单' }]}
            >
              <Input placeholder="请输入关联订单" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="回款金额"
              name="paymentAmount"
              rules={[{ required: true, message: '请输入回款金额' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                step={0.01}
                placeholder="请输入回款金额"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={8}>
            <Form.Item
              label="国家日期"
              name="countryDate"
              rules={[{ required: true, message: '请选择国家日期' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="回款频次"
              name="paymentFrequency"
              rules={[{ required: true, message: '请选择回款频次' }]}
            >
              <Select placeholder="请选择回款频次">
                <Option value="月度">月度</Option>
                <Option value="季度">季度</Option>
                <Option value="年度">年度</Option>
                <Option value="一次性">一次性</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="回款计划"
              name="paymentPlan"
            >
              <Input placeholder="请输入回款计划" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={8}>
            <Form.Item
              label="付款方式"
              name="paymentMethod"
              rules={[{ required: true, message: '请选择付款方式' }]}
            >
              <Select placeholder="请选择付款方式">
                <Option value="银行转账">银行转账</Option>
                <Option value="支付宝">支付宝</Option>
                <Option value="微信支付">微信支付</Option>
                <Option value="现金">现金</Option>
                <Option value="支票">支票</Option>
                <Option value="信用证">信用证</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="回款类型"
              name="paymentType"
              rules={[{ required: true, message: '请选择回款类型' }]}
            >
              <Select placeholder="请选择回款类型">
                <Option value="正常回款">正常回款</Option>
                <Option value="提前回款">提前回款</Option>
                <Option value="延期回款">延期回款</Option>
                <Option value="部分回款">部分回款</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="逾期状态"
              name="overdueStatus"
            >
              <Select placeholder="请选择逾期状态">
                <Option value="未逾期">未逾期</Option>
                <Option value="已逾期">已逾期</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={8}>
            <Form.Item
              label="审批状态"
              name="approvalStatus"
              rules={[{ required: true, message: '请选择审批状态' }]}
            >
              <Select placeholder="请选择审批状态">
                <Option value="待审批">待审批</Option>
                <Option value="已通过">已通过</Option>
                <Option value="被否决">被否决</Option>
                <Option value="被驳回">被驳回</Option>
                <Option value="已撤销">已撤销</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="逾期天数"
              name="overdueDays"
            >
              <InputNumber style={{ width: '100%' }} min={0} placeholder="请输入逾期天数" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="收款人员"
              name="collectionPerson"
            >
              <Input placeholder="请输入收款人员" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={8}>
            <Form.Item
              label="提交人员"
              name="submitter"
            >
              <Input placeholder="请输入提交人员" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="审批人员"
              name="approver"
            >
              <Input placeholder="请输入审批人员" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="通知地点"
              name="notificationRecipients"
            >
              <Input placeholder="请输入通知地点" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="提交时间"
              name="submissionTime"
            >
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="审批时间"
              name="approvalTime"
            >
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={24}>
            <Form.Item
              label="备注信息"
              name="remarks"
            >
              <TextArea rows={4} placeholder="请输入备注信息" />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            更新记录
          </Button>
          <Button
            style={{ marginLeft: 16 }}
            onClick={() => navigate(`/fundsrecoverymanagement/funddetails/${id}`)}
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default UpdateFundsrecovery;